﻿using AutoMapper;
using MediatR;
using System.Transactions;
using Traceability.App.Apilication.Common.Breeding;
using Traceability.App.Domain;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure.Interfance;

namespace Traceability.App.Apilication.Handler.Breeding
{
    public class CreateBreedingEnterHandler : IRequestHandler<CreateBreedingEnterCommon, ApiResult<int>>
    {
        private readonly IBaseRespository<BreedingEnterprises> breedingenterprises;
        private readonly IMapper mapper;

        public CreateBreedingEnterHandler(IBaseRespository<BreedingEnterprises> breedingenterprises,IMapper mapper)
        {
            this.breedingenterprises = breedingenterprises;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(CreateBreedingEnterCommon request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            var model = mapper.Map<BreedingEnterprises>(request);
            model.CreateTime=DateTime.Now;
            var r = 0;
            using(TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                r= breedingenterprises.Add(model).Result;
                tran.Complete();
            }

            if (r > 0)
            {
                res.Code = ApiEnum.Success;
                res.Message = "添加成功";
                return Task.FromResult(res);
            }
            else
            {
                res.Code = ApiEnum.Error;
                res.Message = "添加失败";
                return Task.FromResult(res);
            }


        }
    }
}
